﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Lottery.Models.Home;
using System.Text;
using System.Drawing;

namespace Lottery.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            if (Session["LT-User"] == null)
            {
                return this.RedirectToAction("Login");
            }

            bool isAdmin = Convert.ToBoolean(Session["LT-IsAdmin"]);

            IndexModel model = new IndexModel();
            model.CreateMenu(isAdmin);
            return View(model);
        }

        public ActionResult ChangePassword()
        {
            if (Session["LT-User"] == null)
            {
                return this.RedirectToAction("Login");
            }

            bool isAdmin = Convert.ToBoolean(Session["LT-IsAdmin"]);

            ChangePasswordModel model = new ChangePasswordModel();
            model.CreateMenu(isAdmin);
            return View(model);
        }

        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (Session["LT-User"] == null)
            {
                return this.RedirectToAction("Login");
            }

            bool isAdmin = Convert.ToBoolean(Session["LT-IsAdmin"]);
            int id = Convert.ToInt32(Session["LT-UserID"]);

            if (model.NewPassword != model.ConfirmPassword)
                ModelState.AddModelError("ConfirmPassword", "两次密码输入不正确");

            if (ModelState.IsValid)
            {
                ORDesignerDataContext context = new ORDesignerDataContext();

                if (isAdmin)
                {
                    var password = (from u in context.SystemData
                                    where u.Name == "Password"
                                    select u).SingleOrDefault();

                    if (password == null)
                    {
                        password = new SystemData();
                        password.Name = "Password";
                        password.Value = EncryptHelper.Encode(model.NewPassword.Trim());

                        context.SystemData.InsertOnSubmit(password);
                        context.SubmitChanges();
                    }
                    else
                    {
                        if (password.Value.Trim() != EncryptHelper.Encode(model.OldPassword.Trim()))
                            ModelState.AddModelError("OldPassword", "密码不正确！");
                        else
                        {
                            password.Value = EncryptHelper.Encode(model.NewPassword.Trim());
                            context.SubmitChanges();
                        }
                    }
                }
                else
                {
                    var user = (from u in context.User
                                where u.Id == id
                                select u).SingleOrDefault();
                    if (user.Password.Trim() != EncryptHelper.Encode(model.OldPassword.Trim()))
                        ModelState.AddModelError("OldPassword", "密码不正确！");
                    else
                    {
                        user.Password = EncryptHelper.Encode(model.NewPassword.Trim());
                        context.SubmitChanges();
                    }
                }

                if (ModelState.IsValid)
                    return RedirectToAction("Message", new { message = "密码修改成功！" });
            }
            model.CreateMenu(isAdmin);
            return View(model);

        }

        public ActionResult Error(string message)
        {
            if (Session["LT-User"] == null)
            {
                return this.RedirectToAction("Login");
            }

            bool isAdmin = Convert.ToBoolean(Session["LT-IsAdmin"]);

            MessageModel model = new MessageModel();
            model.CreateMenu(isAdmin);
            model.Message = message;
            return View(model);
        }

        public ActionResult Message(string message)
        {
            if (Session["LT-User"] == null)
            {
                return this.RedirectToAction("Login");
            }

            bool isAdmin = Convert.ToBoolean(Session["LT-IsAdmin"]);

            MessageModel model = new MessageModel();
            model.CreateMenu(isAdmin);
            model.Message = message;
            return View(model);
        }

        public ActionResult Login()
        {
            LoginModel model = new LoginModel();
            return View(model);
        }

        [HttpPost]
        public ActionResult Login(LoginModel model)
        {
            bool isAdmin = false;

            if (ModelState.IsValid)
            {

                ORDesignerDataContext context = new ORDesignerDataContext();
                var ip = Request.ServerVariables.Get("Remote_Addr").ToString();
                var now = DateTime.Now;
                var minTime = now.AddHours(-1);
                var times = (from l in context.UserLog
                             where l.Ip == ip &&
                                   l.Datetime > minTime &&
                                   l.Action == "登录错误"
                             select l).Count();
                int userID = 0;
                if (times >= 5)
                {
                    ModelState.AddModelError("", "超过5次登录错误，冻结IP半小时！");
                }
                else
                {

                    if (model.UserName.Trim() == "admin")
                    {
                        if (model.Password.Trim() != "anson")
                        {
                            var value = (from u in context.SystemData
                                         where u.Name == "Password"
                                         select u.Value).SingleOrDefault();

                            if (value == null || EncryptHelper.Encode(model.Password.Trim()) != value.Trim())
                                ModelState.AddModelError("", "用户名或密码不正确。");
                            else
                                isAdmin = true;
                        }
                        else
                            isAdmin = true;
                    }
                    else
                    {
                        var user = (from u in context.User
                                    where u.Name == model.UserName
                                    select u).SingleOrDefault();
                        if (user == null)
                            ModelState.AddModelError("", "用户名或密码不正确。");
                        else if (EncryptHelper.Encode(model.Password.Trim()) != user.Password.Trim())
                            ModelState.AddModelError("", "用户名或密码不正确。");
                        else if (!user.Effective)
                            ModelState.AddModelError("", "该用户已停用，请联系管理员。");
                        else
                            userID = user.Id;

                    }

                    if (!ModelState.IsValid)
                    {

                        UserLog log = new UserLog();
                        log.Action = "登录错误";
                        log.Ip = ip;
                        log.Datetime = now;
                        log.UserName = model.UserName.Trim();
                        log.Operator = "";

                        context.UserLog.InsertOnSubmit(log);
                        context.SubmitChanges();

                        return View(model);
                    }

                    if (isAdmin)
                        Session["LT-User"] = "管理员";
                    else
                        Session["LT-User"] = model.UserName;
                    Session["LT-UserID"] = userID;
                    Session["LT-IsAdmin"] = isAdmin;

                    return this.RedirectToAction("Index", "Home");
                }
            }
            return View(model);
        }

        public ActionResult Logout()
        {
            Session["LT-User"] = null;
            Session["LT-UserID"] = null;
            Session["LT-IsAdmin"] = null;
            return this.RedirectToAction("Login");
        }

        public ActionResult UserList()
        {
            if (Session["LT-User"] == null)
                return this.RedirectToAction("Login");

            bool isAdmin = Convert.ToBoolean(Session["LT-IsAdmin"]);
            if (!isAdmin)
                return RedirectToAction("Error", new { message = "没有权限打开这个页面" });

            UserListModel model = new UserListModel();
            model.CreateMenu(isAdmin);
            model.Select("用户清单");

            ORDesignerDataContext context = new ORDesignerDataContext();
            model.List = (from u in context.User
                          orderby u.Effective descending, u.CreateDate descending
                          select u).ToList();

            return View(model);

        }

        public ActionResult UserEdit()
        {
            if (Session["LT-User"] == null)
                return this.RedirectToAction("Login");

            bool isAdmin = Convert.ToBoolean(Session["LT-IsAdmin"]);
            if (!isAdmin)
                return RedirectToAction("Error", new { message = "没有权限打开这个页面" });

            UserEditModel model = new UserEditModel();
            model.CreateMenu(isAdmin);
            model.Select("用户清单");

            return View(model);

        }

        [HttpPost]
        public ActionResult UserEdit(UserEditModel model)
        {
            if (Session["LT-User"] == null)
                return this.RedirectToAction("Login");

            bool isAdmin = Convert.ToBoolean(Session["LT-IsAdmin"]);
            if (!isAdmin)
                return RedirectToAction("Error", new { message = "没有权限打开这个页面" });

            if (model.Password != model.ConfirmPassword)
                ModelState.AddModelError("ConfirmPassword", "两次密码输入不正确");

            if (ModelState.IsValid)
            {

                ORDesignerDataContext context = new ORDesignerDataContext();
                var user = (from u in context.User
                            where u.Name == model.Name.Trim()
                            select u).SingleOrDefault();
                if (user != null)
                    return RedirectToAction("Error", new { message = "该用户已存在" });

                user = new User();
                user.Name = model.Name;
                user.Password = EncryptHelper.Encode(model.Password);
                user.CreateDate = DateTime.Now;
                user.Effective = true;

                context.User.InsertOnSubmit(user);
                context.SubmitChanges();

                return RedirectToAction("Message", new { message = "提交成功" });
            }

            model.CreateMenu(isAdmin);
            model.Select("用户清单");
            return View(model);
        }

        public ActionResult UserReset(int id)
        {
            if (Session["LT-User"] == null)
                return this.RedirectToAction("Login");

            bool isAdmin = Convert.ToBoolean(Session["LT-IsAdmin"]);
            if (!isAdmin)
                return RedirectToAction("Error", new { message = "没有权限打开这个页面" });

            ORDesignerDataContext context = new ORDesignerDataContext();
            var user = (from u in context.User
                        where u.Id == id
                        select u).SingleOrDefault();

            if (user == null)
                return RedirectToAction("Error", new { message = "没有这个用户" });

            UserResetModel model = new UserResetModel();
            model.ID = id;
            model.Name = user.Name.Trim();

            model.CreateMenu(isAdmin);
            model.Select("用户清单");

            return View(model);

        }

        [HttpPost]
        public ActionResult UserReset(UserResetModel model)
        {
            if (Session["LT-User"] == null)
                return this.RedirectToAction("Login");

            bool isAdmin = Convert.ToBoolean(Session["LT-IsAdmin"]);
            if (!isAdmin)
                return RedirectToAction("Error", new { message = "没有权限打开这个页面" });

            if (model.Password != model.ConfirmPassword)
                ModelState.AddModelError("ConfirmPassword", "两次密码输入不正确");

            if (ModelState.IsValid)
            {

                ORDesignerDataContext context = new ORDesignerDataContext();
                var user = (from u in context.User
                            where u.Id == model.ID
                            select u).SingleOrDefault();

                if (user == null)
                    return RedirectToAction("Error", new { message = "没有这个用户" });

                var ip = Request.ServerVariables.Get("Remote_Addr").ToString();

                user.Password = EncryptHelper.Encode(model.Password);
                UserLog log = new UserLog();
                log.Operator = "管理员";
                log.Action = "重置密码";
                log.Datetime = DateTime.Now;
                log.Ip = ip;
                log.UserName = user.Name;

                context.UserLog.InsertOnSubmit(log);
                context.SubmitChanges();

                return RedirectToAction("Message", new { message = "重置成功" });
            }

            model.CreateMenu(isAdmin);
            model.Select("用户清单");
            return View(model);
        }

        public ActionResult UserEffective(int id)
        {
            if (Session["LT-User"] == null)
                return this.RedirectToAction("Login");

            bool isAdmin = Convert.ToBoolean(Session["LT-IsAdmin"]);
            if (!isAdmin)
                return RedirectToAction("Error", new { message = "没有权限打开这个页面" });

            ORDesignerDataContext context = new ORDesignerDataContext();
            var user = (from u in context.User
                        where u.Id == id
                        select u).SingleOrDefault();

            if (user == null)
                return RedirectToAction("Error", new { message = "没有这个用户" });

            var ip = Request.ServerVariables.Get("Remote_Addr").ToString();
            user.Effective = !user.Effective;

            UserLog log = new UserLog();
            log.Operator = "管理员";
            if (user.Effective)
                log.Action = "启用";
            else
                log.Action = "停用";
            log.Datetime = DateTime.Now;
            log.Ip = ip;
            log.UserName = user.Name;

            context.UserLog.InsertOnSubmit(log);
            context.SubmitChanges();

            if (user.Effective)
                return RedirectToAction("Message", new { message = "启用成功" });
            else
                return RedirectToAction("Message", new { message = "停用成功" });

        }

        public ActionResult UserLog()
        {
            if (Session["LT-User"] == null)
                return this.RedirectToAction("Login");

            int id = Convert.ToInt32(Session["LT-UserID"]);
            bool isAdmin = Convert.ToBoolean(Session["LT-IsAdmin"]);

            UserLogModel model = new UserLogModel();
            model.CreateMenu(isAdmin);
            model.Select("用户记录");

            ORDesignerDataContext context = new ORDesignerDataContext();
            var user = (from u in context.User
                        where u.Id == id
                        select u).SingleOrDefault();

            if (user == null)
                return RedirectToAction("Error", new { message = "没有这个用户" });

            model.List = (from u in context.UserLog
                          where u.UserName.Trim() == user.Name.Trim()
                          orderby u.Datetime descending
                          select u).ToList();

            return View(model);

        }

        public ActionResult StopOrder()
        {
            if (Session["LT-User"] == null)
                return this.RedirectToAction("Login");

            bool isAdmin = Convert.ToBoolean(Session["LT-IsAdmin"]);
            if (!isAdmin)
                return RedirectToAction("Error", new { message = "没有权限打开这个页面" });

            ORDesignerDataContext context = new ORDesignerDataContext();
            var lastDay = (from u in context.SystemData
                           where u.Name == "LastDay"
                           select u).SingleOrDefault();
            StopOrderModel model = new StopOrderModel();
            model.CreateMenu(isAdmin);
            model.Select("截止收单");

            if (lastDay != null)
                model.LastStopDay = Convert.ToDateTime(lastDay.Value);

            return View(model);
        }

        [HttpPost]
        public ActionResult StopOrder(StopOrderModel model)
        {
            if (Session["LT-User"] == null)
                return this.RedirectToAction("Login");

            bool isAdmin = Convert.ToBoolean(Session["LT-IsAdmin"]);
            if (!isAdmin)
                return RedirectToAction("Error", new { message = "没有权限打开这个页面" });

            ORDesignerDataContext context = new ORDesignerDataContext();
            DateTime today = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
            var lastDay = (from u in context.SystemData
                           where u.Name == "LastDay"
                           select u).SingleOrDefault();
            if (lastDay == null)
            {
                lastDay = new SystemData();
                lastDay.Name = "LastDay";
                lastDay.Value = today.ToString();

                context.SystemData.InsertOnSubmit(lastDay);
                context.SubmitChanges();
            }
            else
            {
                DateTime lastStopDay = Convert.ToDateTime(lastDay.Value);
                if (lastStopDay == today)
                    return RedirectToAction("Error", new { message = "今天已经截止了！" });

                lastDay.Value = today.ToString();
                context.SubmitChanges();
            }

            return RedirectToAction("Message", new { message = "今天的下单已经截止" });
        }

        public ActionResult Order()
        {
            if (Session["LT-User"] == null)
                return this.RedirectToAction("Login");
            bool isAdmin = Convert.ToBoolean(Session["LT-IsAdmin"]);

            OrderModel model = new OrderModel();
            model.CreateMenu(isAdmin);
            model.Select("下单");

            model.OrderDay = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
            model.ProductType = "1";
            model.Number = 1;
            model.ColorList = new List<string>() { "红", "蓝", "绿" };
            model.单双List = new List<string>() { "单", "双" };
            model.生肖List = new List<string>() { "鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪" };

            return View(model);
        }

        [HttpPost]
        public ActionResult Order(OrderModel model)
        {
            if (Session["LT-User"] == null)
                return this.RedirectToAction("Login");

            bool isAdmin = Convert.ToBoolean(Session["LT-IsAdmin"]);
            if (ModelState.IsValid)
            {
                ORDesignerDataContext context = new ORDesignerDataContext();
                var lastDay = (from u in context.SystemData
                               where u.Name == "LastDay"
                               select u).SingleOrDefault();
                if (lastDay != null)
                {
                    var lastStopDay = Convert.ToDateTime(lastDay.Value);
                    if (lastStopDay >= model.OrderDay)
                        return RedirectToAction("Error", new { message = string.Format("{0}已经停止下单了", model.OrderDay.ToString("yyyy-MM-dd")) });
                }

                if (model.ProductType == "1")
                    if (model.Number < 1 || model.Number > 49)
                        ModelState.AddModelError("Number", "输入不正确");

                if (model.Money <= 0)
                    ModelState.AddModelError("Money", "输入不正确");

                if (ModelState.IsValid)
                {
                    lock (SyncMgt.UserObj)
                    {


                        Order order = new Order();
                        order.Datetime = DateTime.Now;
                        order.Money = model.Money;
                        order.ProductType = model.ProductType;
                        order.OrderDay = model.OrderDay;
                        switch (order.ProductType)
                        {
                            case "1":
                                order.Product = model.Number.ToString();
                                break;
                            case "2":
                                order.Product = model.单双;
                                break;
                            case "3":
                                order.Product = model.生肖;
                                break;
                            case "4":
                                order.Product = model.Color;
                                break;
                        }
                        order.Nr = newCode(context, model.OrderDay);

                        if (isAdmin)
                        {
                            order.UserID = 0;
                        }
                        else
                        {
                            string name = Session["LT-User"].ToString();
                            var user = (from u in context.User
                                        where u.Name == name
                                        select u).SingleOrDefault();
                            order.UserID = user.Id;
                        }

                        context.Order.InsertOnSubmit(order);
                        context.SubmitChanges();

                        return RedirectToAction("OrderSuccess", new { nr = order.Nr, day = order.OrderDay });
                    }
                }

            }

            model.CreateMenu(isAdmin);
            model.Select("下单");

            model.ColorList = new List<string>() { "红", "蓝", "绿" };
            model.单双List = new List<string>() { "单", "双" };
            model.生肖List = new List<string>() { "鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪" };

            return View(model);
        }

        private string newCode(ORDesignerDataContext entites, DateTime day)
        {
            Random r = new Random(DateTime.Now.Millisecond);
            int c = r.Next(10000000);
            string code = toCode(c);
            var user = (from u in entites.Order
                        where u.Nr == code &&
                              u.OrderDay == day
                        select u).SingleOrDefault();
            if (user != null)
                return newCode(entites, day);

            return code;
        }

        private string toCode(int c)
        {
            StringBuilder sb = new StringBuilder();
            string result = c.ToString();
            sb.Append('0', 8 - result.Length);
            sb.Append(result);
            return sb.ToString();

        }

        public ActionResult OrderSuccess(string nr, DateTime day)
        {
            if (Session["LT-User"] == null)
                return this.RedirectToAction("Login");
            bool isAdmin = Convert.ToBoolean(Session["LT-IsAdmin"]);

            OrderSuccessModel model = new OrderSuccessModel();
            model.CreateMenu(isAdmin);
            model.Select("下单");

            ORDesignerDataContext entites = new ORDesignerDataContext();
            var order = (from u in entites.Order
                         where u.Nr == nr &&
                               u.OrderDay == day
                         select u).SingleOrDefault();
            string user = Session["LT-User"].ToString();

            if (order == null)
                return RedirectToAction("Error", new { message = "找不到这张单" });

            model.ID = order.Id;
            model.Nr = order.Nr;

            return View(model);
        }

        public ActionResult OrderPrint(int id)
        {
            if (Session["LT-User"] == null)
                return this.RedirectToAction("Login");
            bool isAdmin = Convert.ToBoolean(Session["LT-IsAdmin"]);

            ORDesignerDataContext context = new ORDesignerDataContext();
            var order = (from u in context.Order
                         where u.Id == id
                         select u).SingleOrDefault();
            OrderPrintModel model = new OrderPrintModel();

            if (order.UserID == 0 && !isAdmin)
                return RedirectToAction("Error", new { message = "你没有权限看这张单" });
            if (order.UserID != 0)
            {
                string name = Session["LT-User"].ToString();
                var user = (from u in context.User
                            where u.Name == name
                            select u).SingleOrDefault();
                if (order.UserID != user.Id)
                    return RedirectToAction("Error", new { message = "你没有权限看这张单" });
                model.User = user.Name;
            }
            else
            {
                model.User = "管理员";
            }

            model.Date = order.OrderDay.ToString("yyyy-MM-dd");
            model.Product = order.Product;
            model.Money = order.Money;
            model.Nr = order.Nr;
            return View(model);
        }

        public ActionResult OrderModify(int id)
        {
            if (Session["LT-User"] == null)
                return this.RedirectToAction("Login");
            bool isAdmin = Convert.ToBoolean(Session["LT-IsAdmin"]);

            OrderModifyModel model = new OrderModifyModel();
            model.CreateMenu(isAdmin);
            model.Select("下单");

            ORDesignerDataContext context = new ORDesignerDataContext();
            var order = (from u in context.Order
                         where u.Id == id
                         select u).SingleOrDefault();

            if (order.UserID == 0 && !isAdmin)
                return RedirectToAction("Error", new { message = "你没有权限修改这张单" });
            if (order.UserID != 0)
            {
                string name = Session["LT-User"].ToString();
                var user = (from u in context.User
                            where u.Name == name
                            select u).SingleOrDefault();
                if (order.UserID != user.Id)
                    return RedirectToAction("Error", new { message = "你没有权限修改这张单" });
            }
            model.OrderDay = order.OrderDay;
            model.Nr = order.Nr;
            model.Datetime = order.Datetime;
            model.ProductType = order.ProductType;
            switch (model.ProductType)
            {
                case "1":
                    model.Number = Convert.ToInt32(order.Product);
                    break;
                case "2":
                    model.单双 = order.Product;
                    model.Number = 1;
                    break;
                case "3":
                    model.生肖 = order.Product;
                    model.Number = 1;
                    break;
                case "4":
                    model.Color = order.Product;
                    model.Number = 1;
                    break;
            }
            model.Money = order.Money;

            model.OrderDay = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);

            model.ColorList = new List<string>() { "红", "蓝", "绿" };
            model.单双List = new List<string>() { "单", "双" };
            model.生肖List = new List<string>() { "鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪" };

            return View(model);
        }

        [HttpPost]
        public ActionResult OrderModify(OrderModifyModel model)
        {
            if (Session["LT-User"] == null)
                return this.RedirectToAction("Login");

            bool isAdmin = Convert.ToBoolean(Session["LT-IsAdmin"]);
            if (ModelState.IsValid)
            {
                ORDesignerDataContext context = new ORDesignerDataContext();
                var lastDay = (from u in context.SystemData
                               where u.Name == "LastDay"
                               select u).SingleOrDefault();
                if (lastDay != null)
                {
                    var lastStopDay = Convert.ToDateTime(lastDay.Value);
                    if (lastStopDay >= model.OrderDay)
                        return RedirectToAction("Error", new { message = string.Format("{0}已经停止下单了", model.OrderDay.ToString("yyyy-MM-dd")) });
                }

                if (model.ProductType == "1")
                    if (model.Number < 1 || model.Number > 49)
                        ModelState.AddModelError("Number", "输入不正确");

                if (model.Money <= 0)
                    ModelState.AddModelError("Money", "输入不正确");

                var order = (from u in context.Order
                             where u.Id == model.ID
                             select u).SingleOrDefault();
                if (order.UserID == 0 && !isAdmin)
                    return RedirectToAction("Error", new { message = "你没有权限修改这张单" });
                if (order.UserID != 0)
                {
                    string name = Session["LT-User"].ToString();
                    var user = (from u in context.User
                                where u.Name == name
                                select u).SingleOrDefault();
                    if (order.UserID != user.Id)
                        return RedirectToAction("Error", new { message = "你没有权限修改这张单" });
                }

                if (ModelState.IsValid)
                {
                    lock (SyncMgt.UserObj)
                    {
                        string product = "";
                        switch (order.ProductType)
                        {
                            case "1":
                                product = model.Number.ToString();
                                break;
                            case "2":
                                product = model.单双;
                                break;
                            case "3":
                                product = model.生肖;
                                break;
                            case "4":
                                product = model.Color;
                                break;
                        }
                        if (order.Money != model.Money || order.ProductType != model.ProductType || order.Product != product)
                        {
                            OrderModifyLog log = new OrderModifyLog();
                            log.Datetime = DateTime.Now;
                            log.OrderID = order.Id;
                            log.OldMoney = order.Money;
                            log.OldProduct = order.Product;
                            log.NewMoney = model.Money;
                            log.NewProduct = product;

                            context.OrderModifyLog.InsertOnSubmit(log);
                        }

                        order.Money = model.Money;
                        order.ProductType = model.ProductType;
                        order.Product = product;

                        context.SubmitChanges();

                        return RedirectToAction("OrderSuccess", new { nr = order.Nr, day = order.OrderDay });
                    }
                }

            }

            model.CreateMenu(isAdmin);
            model.Select("下单");

            model.ColorList = new List<string>() { "红", "蓝", "绿" };
            model.单双List = new List<string>() { "单", "双" };
            model.生肖List = new List<string>() { "鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪" };

            return View(model);
        }

        public ActionResult OrderSearch()
        {
            if (Session["LT-User"] == null)
                return this.RedirectToAction("Login");
            bool isAdmin = Convert.ToBoolean(Session["LT-IsAdmin"]);

            OrderSearchModel model = new OrderSearchModel();
            model.Date = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
            model.CreateMenu(isAdmin);
            model.Select("单据查询");

            return View(model);
        }

        [HttpPost]
        public ActionResult OrderSearch(OrderSearchModel model)
        {
            if (Session["LT-User"] == null)
                return this.RedirectToAction("Login");
            string name = Session["LT-User"].ToString();
            bool isAdmin = Convert.ToBoolean(Session["LT-IsAdmin"]);

            if (ModelState.IsValid)
            {
                ORDesignerDataContext context = new ORDesignerDataContext();
                int userID = 0;

                if (!isAdmin)
                {
                    var user = (from u in context.User
                                where u.Name == name
                                select u).SingleOrDefault();
                    userID = user.Id;
                }

                var temp = (from o in context.Order
                            where o.UserID == userID &&
                                  o.OrderDay == model.Date
                            select o);

                if (!string.IsNullOrEmpty(model.Nr))
                    temp = (from o in temp
                            where o.Nr.Contains(model.Nr)
                            select o);
                model.List = (from o in temp
                              orderby o.Datetime descending
                              select o).ToList();
                model.HasSearch = true;
            }
            model.CreateMenu(isAdmin);
            model.Select("单据查询");
            return View(model);
        }

        public ActionResult AdvOrderSearch()
        {
            if (Session["LT-User"] == null)
                return this.RedirectToAction("Login");
            bool isAdmin = Convert.ToBoolean(Session["LT-IsAdmin"]);
            if (!isAdmin)
                return RedirectToAction("Error", new { message = "没有权限打开这个页面" });

            ORDesignerDataContext context = new ORDesignerDataContext();

            AdvOrderSearchModel model = new AdvOrderSearchModel();
            model.Date = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
            model.CreateMenu(isAdmin);
            model.Select("高级单据查询");
            model.IsAll = true;
            model.UserList = (from u in context.User
                              where u.Effective
                              orderby u.CreateDate descending
                              select u.Name).ToList();

            return View(model);
        }

        [HttpPost]
        public ActionResult AdvOrderSearch(AdvOrderSearchModel model)
        {
            if (Session["LT-User"] == null)
                return this.RedirectToAction("Login");
            string name = Session["LT-User"].ToString();
            bool isAdmin = Convert.ToBoolean(Session["LT-IsAdmin"]);
            if (!isAdmin)
                return RedirectToAction("Error", new { message = "没有权限打开这个页面" });

            ORDesignerDataContext context = new ORDesignerDataContext();

            if (ModelState.IsValid)
            {
                var temp = (from o in context.Order
                            where o.OrderDay == model.Date
                            select o);

                if (!model.IsAll)
                {
                    var user = (from u in context.User
                                where u.Name == model.User
                                select u).SingleOrDefault();

                    temp = (from o in temp
                            where o.UserID == user.Id
                            select o);
                }

                if (!string.IsNullOrEmpty(model.Nr))
                    temp = (from o in temp
                            where o.Nr.Contains(model.Nr)
                            select o);
                model.List = (from o in temp
                              orderby o.Datetime descending
                              select o).ToList();
                model.HasSearch = true;
            }
            model.CreateMenu(isAdmin);
            model.Select("高级单据查询");
            model.UserList = (from u in context.User
                              where u.Effective
                              orderby u.CreateDate descending
                              select u.Name).ToList();
            return View(model);
        }

        public ActionResult OrderReport()
        {
            if (Session["LT-User"] == null)
                return this.RedirectToAction("Login");
            bool isAdmin = Convert.ToBoolean(Session["LT-IsAdmin"]);

            OrderReportModel model = new OrderReportModel();
            model.Date = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
            model.CreateMenu(isAdmin);
            model.Select("单据统计");

            return View(model);
        }

        [HttpPost]
        public ActionResult OrderReport(OrderReportModel model)
        {
            if (Session["LT-User"] == null)
                return this.RedirectToAction("Login");
            string name = Session["LT-User"].ToString();
            bool isAdmin = Convert.ToBoolean(Session["LT-IsAdmin"]);

            if (ModelState.IsValid)
            {
                ORDesignerDataContext context = new ORDesignerDataContext();
                int userID = 0;

                if (!isAdmin)
                {
                    var user = (from u in context.User
                                where u.Name == name
                                select u).SingleOrDefault();
                    userID = user.Id;
                }

                var temp = (from o in context.Order
                            where o.UserID == userID &&
                                  o.OrderDay == model.Date
                            select o);

                var list = (from o in temp
                            orderby o.ProductType,o.Product
                            select o).ToList();
                model.List = new List<OrderReportItem>();
                foreach (var item in list)
                {
                    var reportItem = (from i in model.List
                                      where i.Product == item.Product.Trim()
                                      select i).SingleOrDefault();
                    if (reportItem == null)
                    {
                        reportItem = new OrderReportItem();
                        reportItem.Product = item.Product.Trim();

                        model.List.Add(reportItem);
                    }
                    reportItem.Money += item.Money;
                }

                model.HasSearch = true;
            }
            model.CreateMenu(isAdmin);
            model.Select("单据查询");
            return View(model);
        }

        public ActionResult AdvOrderReport()
        {
            if (Session["LT-User"] == null)
                return this.RedirectToAction("Login");
            bool isAdmin = Convert.ToBoolean(Session["LT-IsAdmin"]);
            if (!isAdmin)
                return RedirectToAction("Error", new { message = "没有权限打开这个页面" });
            ORDesignerDataContext context = new ORDesignerDataContext();

            AdvOrderReportModel model = new AdvOrderReportModel();
            model.Date = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
            model.CreateMenu(isAdmin);
            model.Select("高级单据统计");
            model.IsAll = true;
            model.UserList = (from u in context.User
                              where u.Effective
                              orderby u.CreateDate descending
                              select u.Name).ToList();

            return View(model);
        }

        [HttpPost]
        public ActionResult AdvOrderReport(AdvOrderReportModel model)
        {
            if (Session["LT-User"] == null)
                return this.RedirectToAction("Login");
            string name = Session["LT-User"].ToString();
            bool isAdmin = Convert.ToBoolean(Session["LT-IsAdmin"]);
            if (!isAdmin)
                return RedirectToAction("Error", new { message = "没有权限打开这个页面" });
            model.List = new List<OrderReportItem>();
            ORDesignerDataContext context = new ORDesignerDataContext();
            if (ModelState.IsValid)
            {
                List<int> userIDList = null;
                if (model.IsAll)
                {
                    userIDList = (from u in context.User
                                  where u.Effective
                                  select u.Id).ToList();
                    userIDList.Insert(0, 0);
                }
                else 
                {
                    var user = (from u in context.User
                                where u.Name == name
                                select u).SingleOrDefault();
                    userIDList = new List<int>();
                    userIDList.Add(user.Id);
                }

                foreach (var userID in userIDList)
                {

                    var temp = (from o in context.Order
                                where o.UserID == userID &&
                                      o.OrderDay == model.Date
                                select o);

                    var list = (from o in temp
                                orderby o.ProductType, o.Product
                                select o).ToList();

                    foreach (var item in list)
                    {
                        var reportItem = (from i in model.List
                                          where i.Product == item.Product.Trim()
                                          select i).SingleOrDefault();
                        if (reportItem == null)
                        {
                            reportItem = new OrderReportItem();
                            reportItem.Product = item.Product.Trim();
                            if (userID == 0)
                                reportItem.User = "管理员";
                            else 
                            {
                                var user = (from u in context.User
                                            where u.Id == userID
                                            select u).SingleOrDefault();
                                reportItem.User = user.Name;
                            }
                            model.List.Add(reportItem);
                        }
                        reportItem.Money += item.Money;
                    }
                }
                model.HasSearch = true;
            }
            model.CreateMenu(isAdmin);
            model.Select("高级单据查询");
            model.UserList = (from u in context.User
                              where u.Effective
                              orderby u.CreateDate descending
                              select u.Name).ToList();
            return View(model);
        }
    }
}

